# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import *
from django import newforms as forms
from libs.plug_core import *

# models
from apps.core.models.section import Section
from apps.core.models.element import Element

#forms
from apps.core.backend.views.forms.section_form import SectionForm


@permission_required("is_staff")
def generic_add(request,section_id=None):
    print section_id
    if request.POST:
        return HttpResponseRedirect("/admin/contents/"+section_id+"/"+
                                    request.POST["objtype"]+"/add")
    return HttpResponseRedirect("/admin/contents/"+section_id+"/articles/add")

@permission_required("is_staff")
def add(request, element_type, section_id=None, element_id=None):
    # INSERIMENTO NUOVO ELEMENTO
    if not element_type == 'subsection':
        initial = {'owner' : request.user.id, 'section' : section_id}
        
        if request.POST:
            form = get_form_for_etype(element_type)(request.POST, 
                                                    initial=initial)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect("/admin/contents/")
        else:
            form = get_form_for_etype(element_type)(initial=initial)
        
            default_context = {'form':form, 
                               'title' : 'Aggiungi Articolo', 
                               'type' : 'article'}
        return render_to_response('admin_element_update.html', default_context)
        
    # INSERIMENTO NUOVA SEZIONE|SOTTOSEZIONE    
    else:
        initial = { 'parent':section_id, 'owner':request.user.id }
        
        if request.POST:
            form = SectionForm(data=request.POST, initial = initial)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect("/admin/contents/")
        else:
            form = SectionForm(initial = initial)
            
        default_context = {'form':form, 
                           'title':'Aggiungi Sottosezione', 
                           'type':'section'}

        return render_to_response('admin_element_update.html', default_context)
    
@permission_required("is_staff")
def update(request, element_type, element_id):
    obj = None
    if not element_type == 'contents':
        try:
            obj = get_model_from_etype(element_type
                                       ).objects.get(
                related_element=element_id)
        except Exception, e:
            print e
            return HttpResponseRedirect("/admin/contents/")
        initial = obj.__dict__
        initial.update(obj.related_element.__dict__)
        initial['section'] = initial['section_id']
        initial['owner'] = initial['owner_id']
        if request.POST:
            #form = ArticleForm(request.POST, initial=initial)
            form = get_form_for_etype(element_type)(request.POST,
                                                    initial=initial)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect("/admin/contents/")
        else:
            form = get_form_for_etype(element_type)(initial=initial)
        
        default_context = {'form':form, 'title' : 'Modifica Articolo', 'type' : 'article'}
        return render_to_response('admin_element_update.html', default_context)         
        
    else:
        try:
            obj = Section.objects.get(id=element_id)
        except:
            return HttpResponseRedirect("/admin/contents/")
        initial = obj.__dict__
        initial['parent']= initial['parent_id']
        #initial['order'] = initial['order_id']
        initial['owner'] = initial['owner_id']        
        if request.POST:
            form = SectionForm(data=request.POST, initial=initial)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect("/admin/contents/")
        else:
            form = SectionForm(initial=initial)
        
        default_context = {'form':form, 'title' : 'Modifica Sezione', 'type' : 'section'}
        return render_to_response('admin_element_update.html', default_context)          
        
    return HttpResponseRedirect("/admin/contents/")

@permission_required("is_staff")
def delete(request, element_type, element_id):
    obj = None
    if not element_type == 'contents':
        obj = Element.objects.all().filter(id=element_id)
        mname = get_entity(obj[0]).lower()+"_set"
        method = getattr(obj[0],mname)
        obj1 = method.all()
        try:
            if obj1:
                obj1.delete()
            obj.delete()
        except:
            pass
    else:
        obj = Section.objects.all().filter(id=element_id)
        try:
            obj[0].delete()
        except:
            pass
    return HttpResponseRedirect("/admin/contents/")


@permission_required("is_staff")
def move(request, element_type, element_id, direction):
    try:
        obj = Section.objects.get(pk=element_id)
       
        if direction == 'up':
            obj.order += 1
        elif direction == 'down':
            if obj.order > 0:
                obj.order -= 1 
        obj.save()
    except Exception, e:
        print e
    return HttpResponseRedirect("/admin/contents/")
